import React, { useState } from "react";
import ProForm, { ProFormText } from "@ant-design/pro-form";
import MusicAPI from '@/services/ant-design-pro/music';
import { Modal, message } from 'antd'
import { connect } from 'dva'

const { addLyricAuthor, updateLyricAuthor } = MusicAPI;
const CreateOrEdit = (props) => {
    const { isModalVisible, isShowModal, actionRef, setData, initData, dispatch } = props;
    const type = initData === undefined ? "添加" : "编辑";
    /**
     * 添加或编辑词作家
     * @param {obj} params 参数
     * @returns 
     */
    const handleSubmit = async (params) => {
        let result;
        if (initData === undefined) { // 添加
            result = await addLyricAuthor(params);
        } else { // 编辑
            let i = 0;
            for (let key in params) {
                if (params[key] == initData[key]) {
                    i++;
                }
            }
            if (i >= 1)
                return message.error("您还未修改数据")

            result = await updateLyricAuthor({
                ...initData,
                ...params,
            });
        }

        if (result.status == 'ok') {
            await setData();
            actionRef.current.reload();
            message.success(type + "成功");
            dispatch({
                type: 'music/refreshSelect',
                payload: {
                    key: 'LyricAuthor',
                    refresh: true
                }
            });
        } else {
            message.error(type + '失败：' + result.data.message);
            console.log(result.data.error);
        }
        isShowModal(false);
    }

    return (<Modal
        title={`${type}词作家`}
        footer={false}
        visible={isModalVisible}
        onCancel={() => isShowModal(false)}
        destroyOnClose={true}>
        {
            <ProForm
                onFinish={(values) => handleSubmit(values)}
                initialValues={initData}
            >
                <ProFormText
                    name="lyric_author_name"
                    label="词作家名称"
                    placeholder="请输入名称"
                    rules={[
                        { required: true, message: "请输入名称" }
                    ]}
                />
            </ProForm>
        }
    </Modal>);
}

export default connect(({ music }) => ({ music }))(CreateOrEdit);